<template>
  <el-container id="group-query">
    <el-header class="group-query-header">
      <v-header
        ref="vHeader"
        title="用户分群"
        :saveShow="true"
        :showDownloadBtn="false"
        @on-save="saveValue"></v-header>
    </el-header>

    <el-container class="content-wrap">
      <el-container class="content">
        <!-- 常用规则查询条件标签 -->
        <el-header class="header content-item">
          <v-pageHeader
            ref="pageHeader"
            num="00"
            itemKey="anal_id"
            itemValue="anal_name"
            :InquireTransCode="InquireTransCode"
            :setTransCode="setTransCode"
            :delTransCode="delTransCode"
            @on-click="showList"></v-pageHeader>
        </el-header>

        <div class="content-item conditions">

          <!-- 暂定移除 标签树 功能，后期可能加上，不要删除 -->
          <!-- <div class="conditions-tree">
            <el-tree
              ref="tree"
              node-key="id"
              show-checkbox
              highlight-current
              :props="conditionsTreeProps"
              :data="conditionsTree"
              @check="handleTreeCheckChange"></el-tree>
          </div> -->

          <div class="conditions-com">
            <!-- 筛选条件 start -->

            <!-- 暂定移除 标签树 功能，后期可能加上，不要删除 -->
            <!-- <v-conditions :conditionsCheckedStatus="conditionsCheckedStatus" :conditions="conditions" @change="handleConditionsChange"></v-conditions> -->

            <v-conditions
              ref="conditionRef"
              :conditions="conditions"
              :dates="dates"
              @change="handleConditionsChange"
              @on-search="handleSearch"
              @on-select-date="getDate"
              @on-cancel-even="handleCancelEven"></v-conditions>

            <!-- 筛选条件 end -->
          </div>
        </div>

        <div class="content-item query-result" v-show="displayQueryResult">
          <!-- echarts图表展示 -->
          <div class="echarts-box">
            <div class="column">
              <h3>查询结果</h3>
            </div>

            <!-- 暂时移除 -->
            <!-- <div class="data-view" v-if="numbersData.length > 0">
              <div class="data-view-item" :key="i" v-for="(item, i) in numbersData">
                <h4 class="title">{{item['vo_name']}}</h4>
                <p class="count">{{item['vo_count']}}</p>
                <p class="all-count" v-show="item.allCount">累计：{{item.allCount}}</p>
                <span type="button" class="iconfont icon-close close-btn" @click="closeDateViewItem(item)"></span>
              </div>
            </div> -->

            <div class="echarts-list" v-if="echartsData.length > 0">
              <div class="echarts-item" :key="i" v-for="(item, i) in echartsData">
                <h3 class="font16">{{item.echartsName}}</h3>
                <v-slider>
                  <chart :key="subI" :style="{'width': '480px'}" :options="subItem" v-for="(subItem, subI) in item.echartsOptions"></chart>
                </v-slider>
                <hr v-if="i < echartsData.length - 1">
              </div>
            </div>

            <!-- 客户信息列表 -->
            <div class="user-list-table" v-if="userListData.length > 0">
              <p style="margin-bottom: 12px; color: #5a5e66;">客户总数：{{userListData.length}}</p>
              <user-list-table
                :pagination="true"
                :paginationConfig="paginationConfig"
                :queryItemDetailURL="queryCustItemDetailURL"
                :userList="userListData"
                @userPic="handleUserPick"
                @currenPageChange="handleCurrentPageChange"
                @similarPeople="handleSimilarPeople"
                @tagsMap="handleTagsMap"></user-list-table>
            </div>
          </div>
        </div>
      </el-container>
    </el-container>
  </el-container>
</template>

<script type="text/ecmascript-6">
import { mapGetters, mapMutations } from 'vuex'
import {
  VHeader,
  VPageHeader,
  VEcharts
} from '../../../components'
import vPie from './components/vPie'
import VConditions from './components/conditions'
import VSlider from './components/slider'
import UserListTable from './components/userListTable'
import api from '../../../api/url'
import ajax from '../../../api/ajax/ajax'
import {getDateTime, scrollTop, nextPage} from '../../../assets/js'
import Msg from '../../../assets/js/msg'

export default {
  name: 'GroupQuery',

  components: {
    VHeader,
    VPageHeader,
    VConditions,
    UserListTable,
    vPie,
    VSlider,
    VEcharts
  },

  provide: {
    combineQueryURL: api.SELECT_COMBINE_QUERY
  },

  computed: {
    ...mapGetters(['custTags'])
  },

  data () {
    return {
      InquireTransCode: api.COMM_USER_GROUP_QUERY_CONDITIONS, // 查询
      setTransCode: api.CANCEL_TAG_TOP, // 设置 / 取消置顶
      delTransCode: api.DEL_COMM_QUERY_TAG, // 删除常用
      queryCustItemDetailURL: api.USER_DETAIL_QUERY, // 查询客户详细信息
      loadingInstance: null,
      displayQueryResult: false,
      dates: [],
      numbersData: [],
      echartsData: [],
      userListData: [],
      conditions: [],
      dataFromBackend: [],
      dateRange: {},
      paginationConfig: {
        initPage: 1,
        pageSize: 10,
        pageSizes: [10, 20, 30, 40, 50]
      }

      // 暂定移除 标签树 功能，后期可能加上，不要删除
      /* conditionsTreeProps: {
        label: function (data, node) {
          return data.name
        }
      },
      conditionsTree: [], */

      // 暂定移除 标签树 功能，后期可能加上，不要删除
      // conditionsCheckedStatus: []
    }
  },

  mounted () {
    // 如果是从 客户画像页面 返回
    if (this.$route.query.isReturn) {
      const cachedData = JSON.parse(window.sessionStorage.getItem('userGroupCachedData'))
      this.conditions = cachedData.conditions
      this.dateRange = cachedData.dateRange
      this.dates = [new Date(this.dateRange.begin), new Date(this.dateRange.end)]
      this.echartsData = cachedData.viewsData.echartsData
      this.numbersData = cachedData.viewsData.numbersData
      this.userListData = cachedData.viewsData.userListData
      this.dataFromBackend = cachedData.dataFromBackend
      this.paginationConfig = cachedData.viewsData.paginationConfig
      this.displayQueryResult = true

      setTimeout(() => {
        const container = document.querySelector('.content')
        const headerNode = document.querySelector('.content .header')
        const conditionsNode = document.querySelector('.content .conditions')
        const queryResultNode = document.querySelector('.content .query-result')
        const userListTableNode = document.querySelector('.content .query-result .user-list-table')

        const headerHeight = parseFloat(window.getComputedStyle(headerNode).height)
        const conditionsHeight = parseFloat(window.getComputedStyle(conditionsNode).height)
        const queryResultHeight = parseFloat(window.getComputedStyle(queryResultNode).height)
        const userListTableHeight = parseFloat(window.getComputedStyle(userListTableNode).height)

        scrollTop(container, Math.abs((headerHeight + conditionsHeight + queryResultHeight) - userListTableHeight), 500)
      }, 0)
      return null
    }

    const date = new Date()
    const custNo = this.$route.query.custNo

    this.dates = [date, date]
    this.dateRange.begin = getDateTime(date, 'day')
    this.dateRange.end = getDateTime(date, 'day')

    ajax.post(api.FETCH_TAGS_DATA)
      .then(res => {
        this.loadingInstance.close()
        this.dataFromBackend = res.data
        const calList = res.data[0]['options']['cal_list']
        let correspondingCondition = {}

        this.conditions = res.data.map(item => {
          const options = item['options']
          const options1 = options['lab_list']
            .map(item => ({label: item['lab_cns'], value: item['sys_lab'] + '-' + item['lab_id']}))
          const options2 = calList
            .map(item => ({label: item['code_value_nm_cns'], value: item['code_id'] + '-' + item['code_value']}))
          const newOptions = {options1, options2}

          // 如果是 从 精确查询页面 点击相似人群查找 跳转到 该页面
          if (custNo && this.custTags.custTags.length > 0 && this.custTags.selecteIds.length > 0) {
            const {selecteIds} = this.custTags
            correspondingCondition = selecteIds.find(o => o['id'] === item['lab_id']) || {}
            if (Array.isArray(correspondingCondition.checkboxsAll)) {
              correspondingCondition.controls = correspondingCondition.checkboxsAll
                .map(arrItem => ({value1: arrItem['lab_id'], value2: arrItem['cal_id'], value3: arrItem['lab_result_id']}))
            }
          }

          const condition = {
            id: item['lab_id'],
            name: item['lab_cns'],
            options: newOptions,
            controls: correspondingCondition.controls || []
          }

          return condition
        })
      })
      .catch(err => {
        this.loadingInstance.close()
        console.error(err)
      })

    this.loadingInstance = this.$loading({fullscreen: false, target: '#group-query'})

    // 暂定移除 标签树 功能，后期可能加上，不要删除
    /* this.conditionsTree = this.conditions.map(item => ({id: item.id, name: item.name}))
    this.conditionsCheckedStatus = this.conditionsTree.map(item => ({id: item.id, checked: false})) */
  },

  beforeDestroy () {
    this.updateCustTags(Object.assign({}, {custTags: this.custTags.custTags}, {selecteIds: []}))
  },

  methods: {
    ...mapMutations(['updateCustTags']),
    showList (val) {
      const tagId = val['anal_id'] || ''
      ajax.post(api.COMM_USER_GROUP_QUERY_CONDITIONS_VAL, {'anal_id': tagId})
        .then(res => {
          this.loadingInstance.close()
          const dateRange = res.data['date_range']
          const conditions = res.data['conditions']

          // 反选 日期选择
          this.dates = [new Date(dateRange.begin), new Date(dateRange.end)]
          this.dateRange = {
            begin: dateRange.begin,
            end: dateRange.end
          }

          // 反选 查询条件
          this.conditions = this.conditions
            .map(item => {
              const conditionFromBackend = conditions.find(itemFromBackend => itemFromBackend.id === item.id)
              const controls = conditionFromBackend.controls
                .map(controlItem => ({value1: controlItem['lab_id'], value2: controlItem['cal_id'], value3: controlItem['lab_result_id']}))

              return Object.assign({}, item, {controls})
            })
        })
        .catch(err => {
          this.loadingInstance.close()
          console.error(err)
        })

      this.loadingInstance = this.$loading({fullscreen: false, target: '.content-item.conditions'})
    },

    getDate (dates) {
      let begin, end
      if (Array.isArray(dates)) {
        try {
          begin = getDateTime(dates[0], 'day')
        } catch (err) {
          begin = ''
        }

        try {
          end = getDateTime(dates[1], 'day')
        } catch (err) {
          end = ''
        }
      } else {
        begin = end = ''
      }
      this.dateRange = {begin, end}
      this.dates = [new Date(begin), new Date(end)]
    },

    closeDateViewItem (item) {
      this.dataViews = this.dataViews.filter(o => o.name !== item.name)
    },

    handleConditionsChange (conditions) {
      this.conditions = conditions
    },

    handleSearch () {
      // 修改页面不会重置为1
      this.paginationConfig.initPage = 1
      if (!(this.dateRange.begin && this.dateRange.end)) {
        Msg.alert('请先选择日期范围')
        return null
      }

      // 查询之前，先 echarts图标部分的清空数据
      this.echartsData = []
      this.numbersData = []
      this.userListData = []
      this.displayQueryResult = false

      const conditions = this.conditions.map(item => {
        const controlsWithFormatted =
          item.controls.map(subItem => ({'lab_id': subItem.value1, 'cal_id': subItem.value2, 'lab_result_id': subItem.value3}))

        return {
          id: item.id,
          name: item.name,
          controls: controlsWithFormatted
        }
      })
      const data = {
        conditions,
        'date_range': {
          begin: this.dateRange.begin,
          end: this.dateRange.end
        }
      }
      ajax.post(api.USER_GROUP_QUERY, data)
        .then(res => {
          this.loadingInstance.close()
          // 如果 没查询到 数据
          if (Object.keys(res.data).length === 0) {
            Msg.alert('没有查询到符合条件的客户，请重新查询！')
            return null
          }

          this.echartsData = this.buildEChartsOptionsData(res.data['chart_data'])
          this.numbersData = res.data['number_data']
          this.userListData = res.data['table_data']
          this.displayQueryResult = true
          this.$nextTick(() => {
            scrollTop(document.querySelector('#group-query .content'), 725, 100)
          })
        }).catch(err => {
          this.loadingInstance.close()
          console.error(err)
        })

      this.loadingInstance = this.$loading({fullscreen: false, target: '.content-wrap .conditions'})
    },

    handleCancelEven () {
      this.conditions = this.conditions
        .map(item => ({id: item.id, name: item.name, options: item.options, controls: []}))
    },

    // 针对后台返回的 echarts 数据处理 -> echarts 数据
    buildEChartsOptionsData (data) {
      let result
      if (!Array.isArray(data)) {
        result = []
        return result
      }

      result = data.map(item => {
        const echartsOptions = (item['lab_list'] || []).map(subItem => {
          const baseOption = {
            title: {
              text: subItem['lab_cns'],
              x: 'center'
            }
          }

          let featureOption = {}

          // 标签数据 echarts展示图形
          switch (subItem['lab_disp_typ']) {
            // 正常文本
            case '0': {
              featureOption = {}
              break
            }
            // 饼图
            case '1': {
              const sources = (subItem['val_list'] || [])
                .map(o => ({name: o['lab_val'], value: o['lab_val_count']}))

              featureOption = {
                tooltip: {
                  trigger: 'item',
                  formatter: '{a} <br/>{b} : {c} ({d}%)'
                },
                legend: {
                  orient: 'vertical',
                  left: 'left',
                  data: sources.map(o => o.name)
                },
                series: [
                  {
                    name: subItem['lab_cns'],
                    type: 'pie',
                    radius: '55%',
                    center: ['50%', '60%'],
                    data: sources,
                    itemStyle: {
                      emphasis: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                      }
                    }
                  }
                ]
              }
              break
            }
            // 柱状图
            case '2': {
              const sources = (subItem['val_list'] || [])
                .map(o => ({name: o['lab_val'], value: o['lab_val_count']}))

              featureOption = {
                color: ['#3398DB'],
                tooltip: {
                  trigger: 'axis',
                  axisPointer: {
                    type: 'shadow'
                  }
                },
                grid: {
                  left: '3%',
                  right: '4%',
                  bottom: '3%',
                  containLabel: true
                },
                xAxis: [
                  {
                    type: 'category',
                    data: sources.map(o => o.name),
                    axisTick: {
                      alignWithLabel: true
                    }
                  }
                ],
                yAxis: [
                  {
                    type: 'value'
                  }
                ],
                series: [
                  {
                    name: subItem['lab_cns'],
                    type: 'bar',
                    barWidth: '60%',
                    data: sources.map(o => o.value)
                  }
                ]
              }
              break
            }
            // 折线图
            case '3': {
              const sources = (subItem['val_list'] || [])
                .map(o => ({name: o['lab_val'], value: o['lab_val_count']}))

              featureOption = {
                tooltip: {
                  trigger: 'axis'
                },
                xAxis: {
                  type: 'category',
                  data: sources.map(o => o.name)
                },
                yAxis: {
                  type: 'value'
                },
                series: [{
                  data: sources.map(o => o.value),
                  type: 'line'
                }]
              }
              break
            }
            // 雷达图
            case '4': {
              break
            }
            // 地域图
            case '5': {
              break
            }
          }

          const option = Object.assign({}, baseOption, featureOption)
          return option
        })
        return {echartsName: item['lab_cns'], echartsOptions}
      })

      return result
    },

    saveValue (commObj) {
      if (!(this.dateRange.begin && this.dateRange.end)) {
        Msg.alert('请先选择日期范围')
        return null
      }

      const conditions = this.conditions.map(item => {
        const controlsWithFormatted =
          item.controls.map(subItem => ({'lab_id': subItem.value1, 'cal_id': subItem.value2, 'lab_result_id': subItem.value3}))

        return {
          id: item.id,
          name: item.name,
          controls: controlsWithFormatted
        }
      })
      const data = {
        conditions,
        'date_range': {
          begin: this.dateRange.begin,
          end: this.dateRange.end
        },
        'anal_name': commObj.pageHeaderName || '',
        'is_top': commObj.isTop || 'no'
      }

      ajax.post(api.USER_GROUP_QUERY_CONDITIONS_SAVE, data)
        .then(res => {
          Msg.alert('保存成功')

          ajax.post(this.InquireTransCode, {anal_type: '00'})
            .then(res => {
              this.loadingInstance.close()
              this.$refs.pageHeader.getList(res.data)
              this.$refs.vHeader.reset('ruleForm')
            })
            .catch(err => {
              this.loadingInstance.close()
              console.error(err)
            })
        })
        .catch(err => {
          Msg.alert('保存失败')
          console.error(err)
        })

      this.loadingInstance = this.$loading({fullscreen: false, target: '#group-query'})
    },

    handleSimilarPeople (custNo) {
      const { selecteIds } = this.custTags
      let correspondingCondition
      this.conditions = this.conditions.map(item => {
        correspondingCondition = selecteIds.find(subItem => subItem['id'] === item['id']) || {}
        correspondingCondition.controls = correspondingCondition.checkboxsAll
                .map(arrItem => ({value1: arrItem['lab_id'], value2: arrItem['cal_id'], value3: arrItem['lab_result_id']}))
        return Object.assign({}, item, {controls: correspondingCondition.controls || []})
      })

      scrollTop(document.querySelector('#group-query .content'), 0, 500)
    },

    handleUserPick (obj) {
      const cachedData = {
        conditions: this.conditions,
        dateRange: this.dateRange,
        dataFromBackend: this.dataFromBackend,
        viewsData: {
          echartsData: this.echartsData,
          numbersData: this.numbersData,
          userListData: this.userListData,
          paginationConfig: this.paginationConfig
        }
      }
      window.sessionStorage.setItem('returnPageInUserPortarit', 'groupQuery')
      window.sessionStorage.setItem('userGroupCachedData', JSON.stringify(cachedData))
      nextPage('userPortarit', {'cust_no': obj['cust_no']})
    },

    handleTagsMap (obj) {
      // nextPage('tagMap', {'cust_no': obj['cust_no'], 'cns_name': obj['cns_name']})
      nextPage('tagMap')
    },

    handleCurrentPageChange (currentPage) {
      this.paginationConfig = {...this.paginationConfig, initPage: currentPage}
    }

    // 暂定移除 标签树 功能，后期可能加上，不要删除
    /* handleTreeCheckChange (condition, checkedStatusObj) {
      if (checkedStatusObj && checkedStatusObj.checkedKeys) {
        this.conditionsCheckedStatus.forEach(item => {
          if (checkedStatusObj.checkedKeys.includes(item.id)) {
            item.checked = true
          } else {
            item.checked = false

            // 预留功能，当树种 改标签 取消勾选时，清空 conditions 中改标签对应的值
            if (!this.needEmptyValue) {
              let condition = this.conditions.find(o => o.id === item.id)
              condition.controls = []
            }
          }
        })
      }
    } */
  }
}
</script>

<style lang="stylus" scoped>
#group-query
  height 100%
  overflow hidden

  & > .group-query-header
    padding 0
    height 56px !important

  .content-wrap
    padding 10px 0 20px 10px
    height calc(100% - 56px)

    .content
      width 100%
      overflow-y scroll

      .header
        height 50px !important
        z-index 49 !important

      .content-item
        padding 0 20px
        background-color #fff

      & > .conditions
        border-top 1px solid #d8dce5

        .conditions-tree
          padding 20px 10px
          float left
          width 140px

        .conditions-com
          float left
          width calc(100% - 140px)

        &:after
          content ''
          display block
          clear both

      .query-result
        margin-top 10px

        .echarts-box

          .column > h3
            font-weight 550
            font-size 16px
            color #6C7079
            text-align center

          .data-view
            margin 16px 0

            &:after
              content ''
              display block
              clear both

            .data-view-item
              position relative
              display flex
              flex-flow column nowrap
              justify-content space-around
              float left
              margin-right 20px
              padding 0 20px
              width 160px
              height 160px
              border 1px solid #666

              &:last-of-type
                margin-right 0

              .title
                font-size 18px
                color #333

              .count
                color lightblue
                font-size 22px
                text-align center

              .all-count
                color #666
                font-size 16px

              &:hover .close-btn
                display block

              .close-btn
                position absolute
                top 10px
                right 10px
                display none
                width 16px
                height 16px
                cursor pointer

          .echarts-list
            margin 60px auto
            color #5a5e66

            .echarts-item
              margin-bottom 30px

              &:last-of-type
                margin-bottom 0

          .user-list-table
            margin-bottom 10px
</style>
